package com.zyh.um.aspect;

import com.zyh.um.entity.User;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.UUID;

@Component
@Aspect
public class LoginAspect {
    @Autowired
    private HttpServletRequest request;
    
    private static Logger logger = LoggerFactory.getLogger(LoginAspect.class);
    @Pointcut("execution(* com.zyh.um.controller.FormUserController.userLogin(..))")
    public void login(){}

    @Around("login()")
    public Object aroundLogin(ProceedingJoinPoint joinPoint) throws Throwable {
        Enumeration<String> headerNames = request.getHeaderNames();
        while(headerNames.hasMoreElements()){
            String headerName = headerNames.nextElement();
            System.out.println(headerName+" = " + request.getHeader(headerName));
        }

        //登录时生成本次登录的评估日志
        Object[] args = joinPoint.getArgs();
        User user = (User) args[0];
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String evaluateLog = "WebApplication EVALUATE ["+user.getName()+"] "+uuid+" \""+user.getPassword()+"\" Zhengzhou \"113.65,34.76\" [1500,2800,3100] \"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36\"";
        System.out.println("evaluateLog = " + evaluateLog);
        logger.info(evaluateLog);


        Object result = joinPoint.proceed();

        //登录成功，则生成本次的登录成功日志
        if(result != null){
            String loginSuccessLog = "WebApplication SUCCESS ["+user.getName()+"] "+uuid+" \""+user.getPassword()+"\" Zhengzhou \"113.65,34.76\" [1500,2800,3100] \"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36\"";
            logger.info(loginSuccessLog);
        }
        return result;
    }

}